import { NextRequest, NextResponse } from 'next/server';
import fs from 'fs/promises';
import path from 'path';

// 权限验证函数
function checkPermission(request: NextRequest): { hasPermission: boolean; error?: string } {
    const referer = request.headers.get('referer');
    if (!referer) {
        return { hasPermission: false, error: '缺少来源页面信息' };
    }

    try {
        const url = new URL(referer);
        const pathname = url.pathname;

        // 只允许从management页面访问
        if (pathname !== '/management') {
            return { hasPermission: false, error: '权限不足，仅允许从管理页面访问' };
        }

        return { hasPermission: true };
    } catch (error) {
        return { hasPermission: false, error: '无效的来源页面信息' };
    }
}

export async function POST(request: NextRequest) {
    try {
        // 权限检查
        const permissionCheck = checkPermission(request);
        if (!permissionCheck.hasPermission) {
            return NextResponse.json(
                { success: false, error: permissionCheck.error },
                { status: 403 }
            );
        }

        const { path: filePath, type } = await request.json();

        if (!filePath) {
            return NextResponse.json(
                { success: false, error: '路径参数是必需的' },
                { status: 400 }
            );
        }

        const baseDir = path.join(process.cwd(), 'storage');
        const targetPath = path.join(baseDir, filePath);

        const normalizedTargetPath = path.normalize(targetPath);
        const normalizedBaseDir = path.normalize(baseDir);

        if (!normalizedTargetPath.startsWith(normalizedBaseDir)) {
            return NextResponse.json(
                { success: false, error: '无效的路径' },
                { status: 400 }
            );
        }

        try {
            const stats = await fs.stat(targetPath);

            if (type === 'directory') {
                if (!stats.isDirectory()) {
                    return NextResponse.json(
                        { success: false, error: '指定路径不是文件夹' },
                        { status: 400 }
                    );
                }
                await fs.rmdir(targetPath, { recursive: true });
            } else {
                if (!stats.isFile()) {
                    return NextResponse.json(
                        { success: false, error: '指定路径不是文件' },
                        { status: 400 }
                    );
                }
                await fs.unlink(targetPath);
            }

            return NextResponse.json({ success: true });
        } catch (error) {
            if ((error as NodeJS.ErrnoException).code === 'ENOENT') {
                return NextResponse.json(
                    { success: false, error: '文件或文件夹不存在' },
                    { status: 404 }
                );
            }
            throw error;
        }
    } catch (error) {
        console.error('Error deleting file:', error);
        return NextResponse.json(
            { success: false, error: '删除文件失败' },
            { status: 500 }
        );
    }
} 